"""
  Created by Amor on 2018-08-19
"""
import re

from rest_framework import serializers
from rest_framework.validators import UniqueTogetherValidator

from VueShop.settings import REGEX_MOBILE
from .models import UserFav, UserLeavingMessage, UserAddress
from goods.serializers import GoodsSerializer

__author__ = '骆杨'


class UserFavSerializer(serializers.ModelSerializer):
    user = serializers.HiddenField(default=serializers.CurrentUserDefault())

    class Meta:
        model = UserFav
        validators = [
            UniqueTogetherValidator(
                queryset=UserFav.objects.all(),
                fields=('user', 'goods'),
                message='已经收藏')
        ]

        fields = ('user', 'goods', 'id')


class UserFavDetailSerializer(serializers.ModelSerializer):
    goods = GoodsSerializer()

    class Meta:
        model = UserFav
        fields = ('goods', 'id')


class LeavingMessageSerializer(serializers.ModelSerializer):

    user = serializers.HiddenField(default=serializers.CurrentUserDefault())

    add_time = serializers.DateTimeField(read_only=True, format='%Y-%m-%d %H:%M')

    class Meta:
        model = UserLeavingMessage
        fields = '__all__'


class AddressSerializer(serializers.ModelSerializer):
    user = serializers.HiddenField(default=serializers.CurrentUserDefault())

    def validate_signer_mobile(self, signer_mobile):

        if not re.match(REGEX_MOBILE, signer_mobile):
            raise serializers.ValidationError('手机验证非法')
        return signer_mobile

    class Meta:
        model = UserAddress
        fields = '__all__'
